const Router = require('koa-router');
const router = new Router();
const tool = require('../../tools/tool')
const {db, QueryTypes} = require("../../models/db");

router.post('/deliver/confirmCargo', async ctx => {
    let tenantId = ctx.user.tenantId;
    let cargoId = ctx.request.body.cargoId;
    let uid = ctx.user.id;
    let cname = ctx.user.name;
    let ctime = tool.getTime();
    let cargo = await db.models['cargo'].findOne({
        where: {
            id: cargoId,
            tenantId
        }
    })
    if (!cargo) {
        return ctx.err('未找到配送单');
    }
    await db.transaction(async () => {
        let state = 2;
        let cargo = await db.models['cargo'].findOne({
            where: {
                id: cargoId
            }
        })
        cargo.state = state
        cargo.doneBy = uid
        cargo.doneByName = cname
        cargo.updatedAt = ctime
        await cargo.save()
        let cargoInvoice = await db.models['cargoInvoice'].findOne({
            where: {
                cargoId
            }
        })
        cargoInvoice.state = state
        await cargoInvoice.save()
    })

    return ctx.suc("已完成送货");
})

module.exports = router;
